#!/bin/bash
############################################################################
# @example:
# (1) OK: sh boot.sh run test.jar --server.port=8080
# (2) OK: sh boot.sh start test.jar envs:/home/application-envs.yaml
# (3) ERROR !!! sh boot.sh start test.jar --server.port=8080 envs:/home/application-envs.yaml
# (4) ERROR !!! sh boot.sh start test.jar envs:/home/application-envs.yaml --server.port=8080
# (5) OK: sh boot.sh status test.jar
# (6) OK: sh boot.sh stop test.jar
###########################################################################

command=$1
jar=$2
config=$3

if [[ "$config" =~ ^envs:.* ]]; then
  echo -e "\033[36muse additional environment file: ${config:5}\033[0m"
  config="--spring.config.additional-location=${config:5}"
fi

if [ "$command" == "run" ]; then
  echo "java -jar $jar $config"
  java -jar $jar $config
else
  if [ "$command" == "start" ]; then
    echo "nohup java -jar $jar $config >/dev/null 2>&1 &"
    nohup java -jar $jar $config >/dev/null 2>&1 &
  else
    if [ "$command" == "stop" ]; then
      pid=$(ps -ef | grep $jar | grep -v grep | grep -v boot.sh | awk '{ print $2 }')
      if [ -z "$pid" ]; then
        echo $jar is not running
      else
        kill $pid
        echo "$jar ($pid) has stopped"
      fi
    else
      if [ "$command" == "status" ]; then
        echo "ps -ef | grep $jar | grep -v grep | grep -v boot.sh"
        pid=$(ps -ef | grep $jar | grep -v grep | grep -v boot.sh | awk '{ print $2 }')
        if [ -z "$pid" ]; then
          echo -e "\n$jar is stopped"
        else
          echo ""
          ps -ef | grep $jar | grep -v grep | grep -v boot.sh
          echo -e "\n$jar is running"
        fi
      else
        echo "unknown command $command !!!"
      fi
    fi
  fi
fi
